<?php

namespace app\api\controller;

use app\api\model\AuthGroup;
use app\api\model\AuthMenu;
use app\api\model\Manager;
use think\facade\Validate;
use app\common\logic\Data;
use app\lib\Result;

class Roles extends Base
{
  /**
   * 用户组首页列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function index()
  {
    $rule = [
      'pageNo'  => 'number',
      'title'  => 'chsDash',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'type' => input('param.status', 0, 'trim'),
      'pageSize' => input('param.pageSize', 10, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $where[] = ['mid', '=', $this->p_mid];
    if ($data['type'] == 1) {
      $where[] = ['status', '=', 1];
    } elseif ($data['type'] == -1) {
      $where[] = ['status', '=', -1];
    }
    if (!empty($data['title'])) {
      $where[] = ['title', 'like', '%' . $data['title'] . '%'];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = AuthGroup::field('id,status,title,desc')->where($where)->order('id', 'asc')->limit($limit, $data['pageSize'])->select()->toArray();
    foreach ($dataList as &$vo) {
      $vo['key'] = $vo['id'];
    }
    $access = static::getAuthMenuList($this->user['alpha_dev']);
    $returnData['list'] = $dataList;
    $returnData['totalCount'] = AuthGroup::where($where)->count('id');
    $returnData['access'] = $access;
    return Result::Success($returnData);
  }
  /**
   * 获取单条用户组信息
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function getGroupInfo()
  {
    $rule = [
      'id'  => 'require|number',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $infoData = static::getAGroupInfo($data['id'], $this->p_mid);
    return json(['code' => 200, 'data' => $infoData, 'msg' => '获取成功']);
  }
  /**
   * 获取用户组信息 内部调用
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  private static function getAGroupInfo($id, $mid)
  {
    $getRulesInfo = getAuthGroupById($id, $mid);
    $returnData['id'] = $getRulesInfo['id'];
    $returnData['title'] = $getRulesInfo['title'];
    $returnData['desc'] = $getRulesInfo['desc'];
    $returnData['rules'] = $getRulesInfo['halfrules'] . ',' . $getRulesInfo['rules'];
    $returnData['rules'] = explode(',', $returnData['rules']);
    $returnData['rules'] = array_filter($returnData['rules']);
    $returnData['status'] = (string) $getRulesInfo['status'];
    unset($returnData['halfrules']);
    return $returnData;
  }
  /**
   * 获取所有权限树形表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  private static function getAuthMenuList($alphaDev = 1)
  {
    // 2为开发者，可以获取所有菜单
    if ($alphaDev == 2) {
      $where[] = ['status','in','1,2,3'];
      // 3为内测用户，仅能获取正常和内测功能菜单
    } elseif ($alphaDev == 3) {
      $where[] = ['status','in','1,3'];
    } else {
      $where[] = ['status','=',1];
    }
    $rulesList = AuthMenu::field('id,title,pid,type')->where($where)->order('sort', ' asc')->select()->toArray();
    foreach ($rulesList as &$vo) {
      $vo['id'] = (string)$vo['id'];
      $vo['key'] = $vo['id'];
      if ($vo['type'] == 3) {
        $vo['isLeaf'] = true;
      }
      unset($vo['type']);
    }
    $access = Data::listToTreeMulti($rulesList, 0, 'id', 'pid', 'children');
    return $access;
  }
  /**
   * 编辑用户组
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function editAuthGroup()
  {
    $data = [
      'id' => input('param.id', '', 'trim'),
      'title' => input('param.title', '', 'trim'),
      'status' => input('param.status', '', 'trim'),
      'desc' => input('param.desc', '', 'trim'),
      'rules' => input('param.rules', '', 'trim'),
      'halfrules' => input('param.halfKey', '', 'trim'),
    ];
    if (request()->isPost()) {
      $rule = [
        'id|角色ID'  => 'require|number',
        'title|角色名称'  => 'require|chsDash',
        'desc|角色说明'  => 'chsDash',
        'status|状态'  => 'require|number',
        'rules|权限列表'  => 'require',
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['updateTime'] = time();
      delRedisCache('authGroup:id:' . $this->p_mid . '-' . $data['id']);
      delRedisCache('authGroupList:Mid:' . $this->p_mid);
      $status = AuthGroup::where('id', $data['id'])->where('mid', $this->p_mid)->update($data);
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => '修改成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => '角色数据与原数据一致，本次操作失败']);
      }
    } else {
      $getRulesInfo = getAuthGroupById($data['id'], $this->p_mid);
      $getRulesInfo['rules'] = explode(',', $getRulesInfo['rules']);
      $getRulesInfo['halfrules'] = explode(',', $getRulesInfo['halfrules']);
      $getRulesInfo['status'] = (string)$getRulesInfo['status'];
      // unset($getRulesInfo['halfrules']);
      return json(['code' => 200, 'data' => $getRulesInfo, 'msg' => '获取成功']);
    }
  }
  /**
   * 新增用户角色
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function addAuthGroup()
  {
    if (request()->isPost()) {
      $rule = [
        'title|角色名称'  => 'require|chsDash',
        'desc|角色说明'  => 'chsDash',
        'status|状态'  => 'require|number',
        'rules|权限列表'  => 'require',
      ];
      $data = [
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'desc' => input('param.desc', '', 'trim'),
        'rules' => input('param.rules', '', 'trim'),
        'halfrules' => input('param.halfKey', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['updateTime'] = time();
      $data['mid'] = $this->p_mid;
      delRedisCache('authGroupList:Mid:' . $this->p_mid);
      $status = AuthGroup::insert($data);
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => '新增成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => '新增失败，请稍后重试']);
      }
    }
  }
  /**
   * 删除用户角色
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function delAuthGroup()
  {
    $rule = [
      'id'  => 'number',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    if (empty($data['id'])) {
      return json(['code' => -1, 'data' => '', 'msg' => '角色不存在，删除失败']);
    }
    $hasData = AuthGroup::field('id')->where('id', $data['id'])->where('mid', $this->p_mid)->find();
    if (empty($hasData)) {
      return json(['code' => -2, 'data' => '', 'msg' => '角色不存在，删除失败']);
    }
    $hasUser = Manager::field('id,phone')->where('groupId', $data['id'])->where('manager_id', $this->p_mid)->select()->toArray();
    if (!empty($hasUser)) {
      $userPhone = '';
      foreach ($hasUser as $key => $vo) {
        $userPhone .= $vo['phone'] . ',';
      }
      $userPhone = substr($userPhone, 0, -1);
      return json(['code' => -2, 'data' => '', 'msg' => '该角色已被【' . $userPhone . '】使用，如需删除，请先修改以上用户的角色组']);
    }
    delRedisCache('authGroup:id:' . $this->p_mid . '-' . $data['id']);
    delRedisCache('authGroupList:Mid:' . $this->p_mid);
    $status = AuthGroup::where('id', $data['id'])->where('mid', $this->p_mid)->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  /**
   * 禁用用户组
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function forbidAuthGroup()
  {
    $rule = [
      'id'  => 'number',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    if (empty($data['id'])) {
      return json(['code' => -1, 'data' => '', 'msg' => '角色不存在，禁用失败']);
    }
    $hasData = AuthGroup::field('status')->where('id', $data['id'])->where('mid', $this->p_mid)->find();
    if (empty($hasData)) {
      return json(['code' => -2, 'data' => '', 'msg' => '角色不存在，禁用失败']);
    }
    $hasUser = Manager::field('id,phone')->where('groupId', $data['id'])->where('manager_id', $this->p_mid)->select()->toArray();
    if (!empty($hasUser)) {
      $userPhone = '';
      foreach ($hasUser as $key => $vo) {
        $userPhone .= $vo['phone'] . ',';
      }
      $userPhone = substr($userPhone, 0, -1);
      return json(['code' => -2, 'data' => '', 'msg' => '该角色已被【' . $userPhone . '】使用，如需禁用，请先修改以上用户的角色组']);
    }
    delRedisCache('authGroup:id:' . $this->p_mid . '-' . $data['id']);
    delRedisCache('authGroupList:Mid:' . $this->p_mid);
    if ($hasData['status'] == 1) {
      $status = AuthGroup::where('id', $data['id'])->where('mid', $this->p_mid)->update(['status' => -1]);
      $type = '禁用';
    } else {
      $status = AuthGroup::where('id', $data['id'])->where('mid', $this->p_mid)->update(['status' => 1]);
      $type = '解禁';
    }
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => $type . '成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => $type . '失败，请稍后重试']);
    }
  }
}
